<template>
  <view class="container" :style="appThemeStyle">
    <view class="card-wrap">
      <view class="title">核销门店</view>
      <view class="shop-wrap">
        <view class="left oneline-hide">
          <text class="iconfont">&#xe6bf;</text>
          <text class="name">{{ currentShop.shopName }}</text>
          <text class="name" v-if="!isEmpty(currentStore)">/{{ currentStore.storeName }}</text>
          <text class="name" v-else-if="!isEmpty(counter)">/{{ counter.storeName }}</text>
        </view>
        <view class="right" @click="showShopPopup = true">
          <text>切换门店</text>
          <text class="iconfont icon-arrow-right"></text>
        </view>
      </view>
    </view>
    <view class="card-wrap pd0">
      <view class="coupon-top">
        <view class="photo">
          <image :src="$image(options.couponIcon || '/storeminiapp/coupon_verify_default.png')"></image>
        </view>
        <view class="text">
          <view class="name">{{ options.couponName }}</view>
          <view class="date" v-if="options.effectiveDateType == 2">领取后{{options.relativeDay}}天内有效</view>
          <view class="date" v-else>{{ formatTime(options.effectiveStartTime) }}-{{ formatTime(options.effectiveEndTime) }}</view>
        </view>
      </view>
      <view class="coupon-line">
        <image :src="$image('/storeminiapp/coupon_line.png')"></image>
      </view>
      <view class="coupon-bottom">
        <view class="desc">
          <text>该券为{{ formatScope(options.goodsScope) }}</text>
          <text v-if="options.sceneType !== 2">，满{{options.minConsumeValue}}减{{options.maxDiscountValue}}</text>
        </view>
        <view class="desc">使用场景：{{ formatUseScene(options.sceneType) }}</view>
        <view class="desc" v-if="options.description">券描述：{{options.description}}</view>
        <view class="desc">使用门店：</view>
        <view class="desc">{{ options.shopName }}</view>
      </view>
    </view>
    <view class="footer-fixed">
      <view class="btn-wrapper">
        <u-button type="primary" shape="circle" @click="confirm">核销</u-button>
      </view>
    </view>
    <!-- 门店列表 -->
    <u-popup
      v-model="showShopPopup"
      mode="bottom"
      border-radius="20"
      :safe-area-inset-bottom="true"
      :closeable="true"
      :mask-custom-style="{ background: 'rgba(0, 0, 0, 0.7)' }"
    >
      <view class="popup-content">
        <view class="page-title">选择门店</view>
        <u-search
          shape="square"
          placeholder="请输入门店名称"
          v-model="searchValue"
          :action-style="{
            color: appTheme.mainBg
          }"
          :show-action="true"
          action-text="取消"
          :animation="true"
          @search="onSearch"
          @custom="onClear"
          @clear="onSearch"
        ></u-search>
        <scroll-view class="list m-top20" :scroll-y="true">
          <view
            class="item"
            v-for="(item, index) in shopList"
            :key="index"
            :class="{active: index === shopIndex}"
            @click="selectItem(item, index)"
          >
            <text class="name">{{ item.shopName }}</text>
            <text class="iconfont icon-arrow-right" v-if="item.storeCount"></text>
          </view>
        </scroll-view>
      </view>
    </u-popup>
    <!-- 店铺列表 -->
    <u-popup
      v-model="showStorePopup"
      mode="bottom"
      border-radius="20"
      :safe-area-inset-bottom="true"
      :closeable="true"
      :mask-custom-style="{ background: 'rgba(0, 0, 0, 0.7)' }"
    >
      <view class="popup-content">
        <view class="page-title">选择店铺</view>
        <u-search
          shape="square"
          placeholder="请输入店铺名称"
          v-model="storeValue"
          :show-action="true"
          action-text="取消"
          :animation="true"
          @search="onSearchStore"
          @custom="onClearStore"
          @clear="onSearchStore"
        ></u-search>
        <scroll-view class="list m-top20" :scroll-y="true">
          <view
            class="item"
            v-for="(item, index) in storeList"
            :key="index"
            :class="{active: index === storeIndex}"
            @click="selectStore(item, index)"
          >
            <text class="name">{{ item.storeName }}</text>
            <text class="iconfont selected" v-if="index === storeIndex">&#xe6ad;</text>
          </view>
        </scroll-view>
      </view>
    </u-popup>
  </view>
</template>
<script>

import store from '@/store'
import * as CouponApi from '@/api/order/coupon'
import * as StoreApi from '@/api/store'
import { isEmpty } from '@/utils/util'
import storage from "@/utils/storage";
import { LOGIN_COUNTER, SELECT_PICKUP_ID } from "@/store/mutation-types"

let storeList = []

export default {
  name: "index",
  data() {
    return {
      isEmpty,
      shopList: [],
      showShopPopup: false,
      showStorePopup: false,
      searchValue: '',
      storeValue: '',
      shopIndex: -1,
      currentShop: {},
      storeList: [],
      storeIndex: -1,
      currentStore: {},
      options: {}
    }
  },
  computed: {
    store() {
      return store.getters.store
    },
    shops() {
      return store.getters.shops
    },
    tenant() {
      return store.getters.tenant
    },
    counter() {
      return store.getters.counter
    },
  },
  onLoad(options) {
    if (options) this.options = options
    this.shopList = this.shops.filter(item => item.id !== '0')
    this.currentShop = this.store
    this.shopIndex = this.shopList.findIndex(item => item.id === this.currentShop.id)
    if (!isEmpty(this.counter)) {
      this.currentStore = this.counter
    }
    this.check()
  },
  methods: {
    onSearch() {
      this.shopList = this.shops.filter(item => item.id !== '0')
      if (this.searchValue) {
        this.shopList = this.shopList.filter(item => item?.shopName.includes(this.searchValue))
      }
    },
    onClear() {
      this.searchValue = ''
      this.onSearch()
    },
    async selectItem(item, index) {
      this.shopIndex = index
      this.currentShop = item
      this.currentStore = {}
      store.commit('SET_COUNTER', {})
      store.commit('SET_BUSINESS_TYPE', this.currentShop.id === '0' ? 0 : 1)
      storage.set(LOGIN_COUNTER, 0)
      if (item.storeCount) {
        const { data } = await StoreApi.getStoresList(item.id)
        this.storeList = storeList = item.storeIds ? data.filter(val => item.storeIds.includes(val.storeId)) : data
        this.showShopPopup = false
        this.showStorePopup = true
        return
      }
      this.check()
    },
    onSearchStore() {
      this.storeList = storeList
      if (this.storeValue) {
        this.storeList = this.storeList.filter(item => item?.storeName.includes(this.storeValue))
      }
    },
    onClearStore() {
      this.storeValue = ''
      this.onSearchStore()
    },
    async selectStore(item, index) {
      this.storeIndex = index
      this.currentStore = item
      this.check()
    },
    check() {
      const { verifyCode } = this.options
      if (!verifyCode) return
      const { id: shopId, storeIds, storeCount } = this.currentShop
      const { storeId = '' } = this.currentStore
      if ((storeIds?.length || storeCount) && !storeId) return this.$toast('请选择店铺！')
      const params = { shopId, storeId, verifyCode }
      CouponApi.check(params, { isPrompt: false }).then(({ data }) => {
        if (!data) {
          this.$toast('门店/店铺不在优惠券可用范围内')
          this.useShops()
          return
        }
        if (this.showShopPopup) this.showShopPopup = false
        if (this.showStorePopup) this.showStorePopup = false
        if (this.currentShop.id !== this.store.id || this.currentStore.storeId !== this.counter.storeId) this.onChangeStore()
      }).catch(({ msg }) => {
        this.$toast(msg)
      })
    },
    useShops() {
      CouponApi.getCouponShops({
        verifyCode: this.options.verifyCode,
        shopId: this.currentShop.id
      }, { isPrompt: false, load: false }).then(({ data }) => {
        if (data) {
          const hasMaterShop = data.some(item => item.shopId === '0')
          if (!hasMaterShop) {
            const shops = this.$u.deepClone(this.shops)
            const shopIds = data.map(item => item.shopId)
            this.shopList = shops.filter(item => shopIds.includes(item.id))
            this.shopList.forEach(item => {
              const tmp = data.find(val => item.id === val.shopId)
              if (tmp) {
                item.storeIds = tmp.storeIds
              }
            })
          }
        }
      }).catch(() => {})
    },
    confirm() {
      const { verifyCode, minConsumeValue } = this.options
      const { id: shopId, storeIds, storeCount } = this.currentShop
      const { storeId = '' } = this.currentStore
      if ((storeIds?.length || storeCount) && !storeId) return this.$toast('请选择店铺！')
      const params = {
        shopId,
        storeId,
        verifyCode,
        amount: Number(minConsumeValue || 0)
      }
      CouponApi.pay(params).then(({ data }) => {
        if (data) {
          this.$toast('核销成功')
          setTimeout(() => uni.navigateBack({ delta: 1 }), 1500)
        }
      }).catch(() => {})
    },
    async onChangeStore() {
      StoreApi.changeShops(this.tenant.id, this.currentShop.id).then(async () => {
        const currentStore = this.shops.find(val => val.id === this.currentShop.id)
        store.commit('SET_STORE', currentStore)
        const channelList = currentStore && currentStore?.shopOnlineChannels?.map(item => {
          return {
            thirdChannelId: item.thirdChannelId,
            channelName: item.thirdChannelName
          }
        }) || []
        store.commit('SET_CHANNELS', channelList)
        if (this.currentStore.storeId) {
          const counter = this.storeList.find(val => val.storeId === this.currentStore.storeId)
          store.commit('SET_COUNTER', counter)
          store.commit('SET_BUSINESS_TYPE', 2)
          storage.set(LOGIN_COUNTER, this.currentStore.storeId)
        } else {
          store.commit('SET_COUNTER', {})
          store.commit('SET_BUSINESS_TYPE', this.currentShop.id === '0' ? 0 : 1)
          storage.set(LOGIN_COUNTER, 0)
        }
        try {
          const { data: pickups } = await StoreApi.getPickupList(this.currentShop.id)
          store.commit('SET_PICKUPS', pickups)
          const selectPickupId = storage.get(this.currentShop.id + SELECT_PICKUP_ID)
          const pickup = pickups.find(item => item.pickupId === selectPickupId)
          store.commit('SET_PICKUP', pickup || {})
        } catch (e) { }
        // 相应全局事件订阅: 刷新上级页面数据
        uni.$emit('syncRefresh', true)
      })
    },
    /**
     * 获取优惠券商品范围
     * @param val
     */
    formatScope(val) {
      val = Number(val)
      switch (val) {
        case 1:
          return '单品券'
        case 2:
          return '品类券'
        case 3:
          return '部分可用券'
        case 4:
          return '部分不可用券'
        case 5:
          return '全场券'
      }
      return ''
    },
    /**
     * 转换优惠券使用场景
     * @param val
     */
    formatUseScene(val) {
      val = Number(val)
      switch (val) {
        case 1:
          return '线上使用'
        case 2:
          return '线下使用'
        case 3:
          return '线上使用/线下使用'
      }
      return ''
    },
    /**
     * 转换时间
     * @param val
     */
    formatTime(val) {
      if (val) {
        return val.substring(0, 10).split('-').join('.')
      }
      return ''
    },
  }
}
</script>

<style scoped lang="scss">
.container {
  padding: 24rpx;

  .card-wrap {
    padding: 24rpx;
    background: #fff;
    border-radius: 16rpx;
    margin-bottom: 16rpx;

    &.pd0 {
      padding: 0;
    }

    .title {
      font-size: 30rpx;
      margin-bottom: 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .right {
        display: flex;
        align-items: center;
        font-size: 28rpx;
        color: #999999;

        .iconfont {
          font-size: 30rpx;
          margin-left: 8rpx;
        }
      }
    }

    .shop-wrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
      line-height: 56rpx;

      .left {
        width: calc(100% - 180rpx);
        font-weight: bold;

        .iconfont {
          font-size: 38rpx;
          margin-right: 14rpx;
          vertical-align: middle;
        }

        .name {
          font-size: 30rpx;
          vertical-align: middle;
        }
      }

      .right {
        width: 150rpx;
        display: flex;
        align-items: center;
        font-size: 28rpx;
        color: #999999;

        .iconfont {
          font-size: 30rpx;
          margin-left: 8rpx;
        }
      }
    }

    .coupon-top {
      display: flex;
      align-items: stretch;
      padding: 24rpx;

      .photo {
        width: 136rpx;
        height: 136rpx;
        margin-right: 24rpx;
        flex-shrink: 0;

        image {
          width: 100%;
          height: 100%;
          border-radius: 16rpx;
        }
      }

      .text {
        display: flex;
        flex-direction: column;

        .name {
          font-size: 28rpx;
          font-weight: bold;
        }

        .date {
          font-size: 24rpx;
          color: #666666;
          margin-top: auto;
        }
      }
    }

    .coupon-line {
      height: 32rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .coupon-bottom {
      padding: 0 24rpx 24rpx;

      .desc {
        font-size: 24rpx;
        color: #999999;
        line-height: 40rpx;
      }
    }
  }

  .popup-content {
    padding: 24rpx;

    .page-title {
      text-align: center;
      margin-bottom: 40rpx;
      font-size: 36rpx;
      font-weight: bold;
    }

    .list {
      min-height: 30vh;
      max-height: 65vh;

      .item {
        margin-bottom: 24rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-radius: 16rpx;
        border: 1rpx solid var(--eeeeee, #EEE);
        padding: 24rpx;
        font-size: 26rpx;

        &.active {
          border: 1rpx solid #2D71FD;

          .name {
            font-weight: bold;
          }
        }

        .iconfont {
          font-size: 40rpx;
        }

        .icon-arrow-right {
          color: #999999;
        }

        .selected {
          color: #2D71FD;
        }
      }
    }
  }

  // 底部操作栏
  .footer-fixed {
    position: fixed;
    bottom: var(--window-bottom);
    left: 0;
    right: 0;
    z-index: 11;
    // 设置ios刘海屏底部横线安全区域
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);

    .btn-wrapper {
      padding: 16rpx 32rpx;
    }
  }

  ::-webkit-scrollbar {
    width: 0;
    height: 0;
    color: transparent;
  }
}
</style>
